<template>
  <img
    :data-src="src"
    :src="placeholder"
    :alt="alt"
    :class="imageClass"
    ref="imageRef"
    @load="onLoad"
  />
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  src: {
    type: String,
    required: true
  },
  alt: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"%3E%3Crect fill="%23f3f4f6" width="400" height="300"/%3E%3C/svg%3E'
  },
  imageClass: {
    type: String,
    default: ''
  }
});

const imageRef = ref(null);
const isLoaded = ref(false);

const onLoad = () => {
  isLoaded.value = true;
};

onMounted(() => {
  if (!imageRef.value) return;

  // 使用 Intersection Observer API 实现懒加载
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const img = entry.target;
          const src = img.getAttribute('data-src');
          
          if (src) {
            img.setAttribute('src', src);
            img.removeAttribute('data-src');
          }
          
          observer.unobserve(img);
        }
      });
    },
    {
      rootMargin: '50px', // 提前50px开始加载
    }
  );

  observer.observe(imageRef.value);

  onUnmounted(() => {
    if (imageRef.value) {
      observer.unobserve(imageRef.value);
    }
  });
});
</script>

<style scoped>
img {
  transition: opacity 0.3s ease-in-out;
}

img[data-src] {
  opacity: 0.6;
}
</style>

